package com.jmb.apiplatform.Interceptor;


import com.jmb.apiplatform.exception.LoginException;
import com.jmb.apiplatform.util.RedisUtil;
import com.jmb.apiplatform.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;

import static com.jmb.apiplatform.constant.Constants.TOKEN_PREFIX;

@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TokenUtil tokenUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws LoginException {
        if (!request.getMethod().equalsIgnoreCase("OPTIONS")){
            String token = request.getHeader("Token");
            // 获取userid
            Object userId = request.getHeader("UserId");
            if ("".equals(token) || null==token){
                throw new LoginException("token不能为空,登录失效");
            }
            // 验证token是否有效
            if (!tokenUtil.validateToken(token, request)){
                throw new LoginException("token时间过期,登录失效");
            }
            // 从redis中获取用户信息,然后从中提取token

            HashMap<String, Object> redisUserInfo = (HashMap<String, Object>) redisUtil.get(TOKEN_PREFIX + userId);
            if (redisUserInfo==null){
                throw new LoginException("未从Redis中获取到信息 ,请重新获取");
            }
            String  redisToken = (String) redisUserInfo.get("token");
            if (redisToken==null || !redisToken.equals(token)){
                throw new LoginException("token不存在 ,请重新登录");
            }
            return true;

        }

        return true;
    }
}
